const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require("cors");

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const noticeRouter = require('./routes/notice.js');
const loginRouter = require("./routes/login");
const vertoken = require("./util/token");
const { expressjwt: jwt } = require("express-jwt");

var app = express();
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 解析token获取用户信息
app.use(function (req, res, next) {
  const token = req.headers.authorization;
  if (token == undefined) {
    return next();
  } else {
    vertoken
      .getToken(token)
      .then((data) => {
        req.data = data;
        return next();
      })
      .catch((error) => {
        return next();
      });
  }
});
//验证token是否过期并规定哪些路由不用验证
app.use(
  jwt({
    secret: "zyy",
    algorithms: ["HS256"],
  }).unless({
    path: ["/login"], //除了这个地址，其他的URL都需要验证
  })
);

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/notice', noticeRouter);
app.use("/login", loginRouter);

//当token失效返回提示信息
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("token失效");
  }
});

module.exports = app;
